/**
 * @file share_mem.c
 * @author your name (you@domain.com)
 * @brief 共享内存，父进程读，子进程写
 * @version 0.1
 * @date 2021-08-10
 * 
 * @copyright Copyright (c) 2021
 * 
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

#define BUF_SIZE 1024

#define assert(x, msg)   \
    {                    \
        if (!(x))        \
        {                \
            perror(msg); \
            exit(1);     \
        }                \
    }

int main()
{
    void *buf = mmap(NULL, BUF_SIZE, PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    assert(buf != MAP_FAILED, "mmap");

    pid_t pid = fork();
    assert(pid >= 0, "fork()");

    if (pid == 0)
    {
        // child process
        int i = 0;
        int *p = buf;
        while (i < 10)
        {
            *p = i;
            i++;
            sleep(1);
        }
        assert(munmap(buf, BUF_SIZE) >= 0, "munmap");
        exit(0);
    }
    else
    {
        // parent process
        int *p = buf;
        for(int i = 0; i < 20; i++) {
            printf("i = %d\n", *p);
            sleep(1);
        }
        wait(NULL);
        assert(munmap(buf, BUF_SIZE) >= 0, "munmap");
    }

    exit(0);
}